<div class="widget">
	<div class="widget-header bg-blue">
		<i class="widget-icon icon-notebook"></i> 
		<span class="widget-caption"> 班级管理 </span>
		<div class="widget-buttons">
			<a href="javascript:void(0);" onclick="handlerCancel(this);" title="关闭"
				 data-toggle="dispose" data-refresh-table="#table-classes"> <i class="fa fa-times"></i> </a> 
		</div>
	</div>
	<div class="widget-body">
		<!-- TODO 学员信息 -->
		<div class="widget radius-bordered">
			<div class="widget-header bg-gold">
				<i class="widget-icon icon-notebook"></i> 
				<span class="widget-caption"> 本班学员 </span>
				<div class="widget-buttons buttons-bordered">
					<button type="button" class="btn btn-primary btn-sm" title="签到管理" data-toggle="modal" data-target="#common-modal" data-url="content/eam/classes/dialog/history.html" 
									data-onshow="onHistoryShow" data-onhidden="onHistoryHidden"
								  data-extention="早教班，当天及当天之前可以签到或请假（补签），当天之后只能请假不能签到。">
						<i class="glyphicon glyphicon-calendar"></i> 签到管理
					</button>
					<span class="btn btn-default btn-sm">
						<i class="fa fa-clock-o gray"></i> <span data-now data-format="YYYY-MM-DD HH:mm:ss"></span>
					</span>
				</div>
			</div>
			<div class="widget-body editor-body-sm">
				<table data-ajax="handlerSearch" 
							 data-method="post" 
							 data-id-field="id" 
							 data-unique-id="id" 
							 data-pagination="true" 
							 data-click-to-select="true" 
							 data-side-pagination="server" 
							 data-mobile-responsive="true" 
							 data-form-search="#search-form-student" id="table-student" class="bootstrap-table">
					<thead>
						<tr>
							<th data-field="id" data-visible="false"></th>
							<th data-field="student" 		data-align="center">姓名</th>
							<th data-field="birthday"		data-align="center">生日</th>
							<th data-field="moonage" 		data-align="center">月龄</th>
							<th data-field="totals" 		data-align="center">总课时</th>
							<th data-field="useing" 		data-align="center">已用课时</th>
							<th data-field="rested" 		data-align="center">剩余课时</th>
							<th data-field="toplimit" 	data-align="center" data-formatter="renderTopLimit">总请假次数</th>
							<th data-field="toprested" 	data-align="center" data-formatter="renderTopRested">剩余请假次数</th>
							<th data-field="operator" 	data-align="center" data-width="70" data-formatter="renderLimit" data-table-target="student">操作</th>							
							<th data-field="status" 		data-align="center" data-width="120" data-formatter="renderStatus">当天到课情况</th>
						</tr>
					</thead>
				</table>
			</div>
		</div>
		
		<!-- TODO 基本信息 -->
		<div class="widget radius-bordered mgbt-xs-10">
			<div class="widget-header">
				<i class="widget-icon icon-notebook"></i> 
				<span class="widget-caption"> 基本信息 </span>
			</div>
			<div class="widget-body editor-body-sm editor-body-classes">
				<!-- dynamic data -->
			</div>
		</div>
		
		<!-- TODO 老师信息 -->
		<div class="widget radius-bordered mgbt-xs-10" id="addTeacher">
			<div class="widget-header">
				<i class="widget-icon icon-notebook"></i> 
				<span class="widget-caption"> 本班老师 </span>
				<div class="widget-buttons buttons-bordered">
					<button class="btn btn-default btn-sm" data-toggle="modal" data-target="#common-modal" data-url="content/eam/classes/dialog/teacher.html" data-onshow="onTeacherShow">
						<i class="fa fa-plus"></i>
					</button>
				</div>
			</div>
			<div class="widget-body editor-body-sm editor-body-teacher">
				<form class="table-editor" id="tables-form-teacher" data-validate="false">
					<table data-ajax="handlerSearch" 
								 data-method="post" 
								 data-id-field="id" 
								 data-unique-id="teacherid" 
								 data-pagination="true" 
								 data-click-to-select="true" 
								 data-side-pagination="server" 
								 data-mobile-responsive="true" 
								 data-form-source="#tables-form-teacher" 
								 data-form-target="#editor-form-teacher" 
								 data-form-search="#search-form-teacher" id="table-teacher" class="bootstrap-table">
						<thead>
							<tr>
								<th data-checkbox="true"></th>
								<th data-field="id" data-visible="false"></th>
								<th data-field="name" 		data-align="center">姓名</th>
								<th data-field="sex" 			data-align="center">性别</th>
								<th data-field="mobile" 	data-align="center">手机</th>
								<th data-field="method" 	data-align="center">收费方式</th>
								<th data-field="amount" 	data-align="center">费用</th>
								<th data-field="operator" data-align="center" data-width="100" data-formatter="renderOperator" data-table-target="teacher">操作</th>
							</tr>
						</thead>
					</table>
				</form>
			</div>
		</div>
		
	</div>
</div>

<!-- 提交 表单 ========================================================= -->
<form id="editor-form-classes" action="/miwawa/{dbname}/classes/update" method="post" 
			name="com.app.miwawa.api.eam.entity.Classes" data-custom-action="true">
			<input type="hidden" name="status" value="0">
			<input type="hidden" name="invalid" value="F">
</form>
<form id="editor-form-teacher" action="/miwawa/{dbname}/common/update" method="post" 
			name="com.app.miwawa.api.eam.entity.ClassesCharge">
			<input type="hidden" name="bean['teacherid']" id="teacherid">
			<input type="hidden" name="bean['classesid']" id="classesid">
			<input type="hidden" name="bean['status']" 		value="0">
			<input type="hidden" name="bean['invalid']" 	value="F">
</form>
<form id="editor-form-check" action="/miwawa/{dbname}/common/save" method="post" 
			name="com.app.miwawa.api.eam.entity.StudentCheck">
			<input type="hidden" name="bean['status']" value="0">
			<input type="hidden" name="bean['invalid']" value="F">
</form>

<!-- 查询 表单 ========================================================= -->
<form id="search-form-classestime" action="/miwawa/{dbname}/common/search.json" method="post" 
			name="com.app.miwawa.api.eam.entity.ClassesTime">
			<input type="hidden" name="status" value="0" data-search-group="and" data-search-operation="EQ">
			<input type="hidden" name="invalid" value="F" data-search-group="and" data-search-operation="EQ">
			<input type="hidden" name="classesId" value="0" data-search-group="and" data-search-operation="EQ">
</form>
<form id="search-form-teacher" action="/miwawa/{dbname}/common/search.json" method="post" 
			name="com.app.miwawa.api.eam.entity.view.ClassesTeacher">
			<input type="hidden" name="classesid" value="0" data-search-group="and" data-search-operation="EQ">
</form>
<form id="search-form-student" action="/miwawa/{dbname}/common/search.json" method="post" 
			name="com.app.miwawa.api.eam.entity.view.StudentLesson">
			<input type="hidden" name="item" value="早教" data-search-group="and" data-search-operation="EQ">
			<input type="hidden" name="classesId" value="0" data-search-group="and" data-search-operation="EQ">
			<input type="hidden" data-search-sort="fromDate" data-search-order="desc">
</form>

<script type="text/javascript">
<!--
	require(['domReady'],function(domReady){
		domReady(function () {
			loadClasses();
		});
	});
	
	// 加载班级信息
	var classes = {}, $moment;
	function loadClasses(){
		jQuery.utils.nowtimer();
		
		classes["id"] = jQuery("#table-schedule").data("selectedId");
		
		jQuery(":hidden[name='id']","#search-form-classes").val(classes.id);
		jQuery(":hidden[name='classesId']").val(classes.id);
		jQuery(":hidden[name='classesid']").val(classes.id);
		
		// 加载班级信息
		jQuery("#search-form-classes").loadform("many",{
			"select":function(value, target){
				require(['jquery.plugin.form'],function(form){
					form.chosen(target).select(target,{
						querys:{"invalid_EQ":"F"} 
					},function(chosen){
						jQuery("option:contains('"+value+"')", chosen).attr("selected","selected").trigger('chosen:updated');
					});
				});
			},
			"times":function(week, time, id){
				jQuery("#search-form-classestime").searched({offset:0,limit:0}, {
					success: function(data, status, xhr){
						for(var i in data.rows){
							jQuery("option[value='"+data.rows[i].week+"']", week).attr("selected","selected");
							jQuery(time).val(data.rows[i].time.substring(0,5));
							jQuery(id).val(data.rows[i].id);
						}
					}
				});
			}
		});
		
		// 加载学员列表
		jQuery("#table-student").bootstrapTable();
		
		// 加载老师列表
		jQuery("#table-teacher").bootstrapTable();
	}
	
	function renderLimit(value, row, index){
		return	row.id == "edit" ? value : 
				"<a class='btn btn-info	btn-xs btn-table-op' id='edited' onclick='handlerUpdateLeave(this, \""+index+"\")' data-table-source='#table-teacher' data-rowdata='"+JSON.stringify(row)+"' data-toggle='tooltip' data-placement='top' title='修改最大请假次数'> <i class='ion-compose'></i> </a>"
	}
	function renderTopLimit(value, row, index){
		return	value < "0" ? "" : value;
	}
	
	function renderTopRested(value, row, index){
		if(row.toplimit < 0 ){
			return	value == "0" ? "" : value;
		}else{
			return value;
		}
	}
	
	// 更新请假次数上限
	var student;
	function handlerUpdateLeave(trigger, index){
		jQuery("[data-toggle='tooltip']","#table-student").tooltip("destroy");
		var _opts = jQuery(trigger).data();
		student = _opts.rowdata;
		jQuery("#table-student").bootstrapTable("updateRow",{
			index: index,
			row: createEditRows(_opts.rowdata, _opts.tableSource)
		});
		
		function createEditRows(row, target){
			return {
				id:   		"edit",
	      student: 	row.student,
	      birthday: row.birthday,
	      moonage: 	row.moonage,
	      totals: 	row.totals,
	      useing: 	row.useing,
	      rested: 	row.rested,
	      toplimit: createInputs('toplimit', row.toplimit),
	      toprested:row.toprested,
	      operator: createButtons(),
	      status: 	renderstatus(row.status,row,index)
			};
		}
		// 创建输入框
		function createInputs(name, value){
			if(value < 0){
				 return '<input name="'+name+'" id="'+name+'" class="form-control" value="0">';
			}else{
				 return '<input name="'+name+'" id="'+name+'" class="form-control" value="'+value+'">';
			}
		}
		
		// 渲染班级学员列表的当天签到情况
		function renderstatus(value, row, index){
			if(row.id =="edit" ){
				return value ? '<a class="btn '+(value == '上课'?'btn-success':'btn-danger')+' btn-xs">'+value+","+row.checkDetail+'</a>' : value;
			}
		}
		
		// 创建按钮
 		function createButtons(){
			return ""
				+"<span>"
				+"	<button type='button' class='btn btn-success btn-xs' onclick='handSured()' title='确认'><i class='icon ion-checkmark-circled'></i></button>"
				+"	<button type='button' class='btn btn-danger btn-xs' onclick='handCanced()' title='取消'><i class='icon ion-close-circled'></i></button>"
				+"</span>";
		}
	}
	
	function handSured(){
		if((/^[1-9]\d*|0$/).test(jQuery("#toplimit").val()) == false){
			jQuery.message.warning("请假次数只能为非负整数!");
			return ;
		}else{
			jQuery.ajaxsend({
				url:"/miwawa/{dbname}/common/update".replace("{dbname}", dbname),
				data:{
					entityClass:"com.app.miwawa.api.eam.entity.StudentLeaveLimit",
					"bean":{
						"id":student.leavelimitId,
						"topLimit":jQuery("#toplimit").val()
						}
				},
				success:function(data){
					if(!data.error) {
						jQuery("#table-student").bootstrapTable("refresh");
					}else{
						jQuery.message.warning(data.error);
					}
				}
			});
		}
	}
 		
	function handCanced(){
		jQuery("#table-student").bootstrapTable("refresh");
	}
	
	// 班级信息加载完后回调
	function handlerLoadered(){
		require(['moment','jquery.plugin.form'],function(moment, form){
			$moment = moment;
			form.tooltip("[data-toggle='tooltip']");
			form.datepicker(".date-selector");
			form.datepicker(".time-selector",{format:"HH:mm"});
			form.chosen("#lessonWeek");
			
			classes["name"] = jQuery("#name",".form-editor-classes").val();
		});
	}
	
	// 生成班级名称
	function createName(form){
		var week = jQuery("#lessonWeek").val();
		var time = jQuery("#lessonTime").val();
		var lesson = jQuery("#lesson > option[value='"+jQuery("#lesson").val()+"']").text();
		if((/^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/).test(jQuery("#usecount").val()) == false){
			jQuery.message.warning("耗课数只能为正整数或正小数!");
			return false;
		}else{
			if(form && (week+time+lesson) != jQuery("#name").val()){
				jQuery.message.alert("请修改课程名称（点击班级名称右侧“生成名称”按钮）后，才可保存修改信息。");
				return false;
			}else if(check(week)){
				jQuery.message.alert(week+" "+time+" 已有班级： "+classesname+" 在 "+roomname+" 上课，请修改上课时间或选择其他教室");
				return false;
			}else{
				jQuery("#name").val(week+time+lesson);
				return true;
			}
		}
	}
	
	//检查该时间段该教室是否已有班级上课
	function check(week){
		var stamp = false;
		jQuery.ajax({
			url:"/miwawa/{dbname}/common/search.json".replace("{dbname}",dbname),
			type:"POST",
			dataType:"json",
			async:false,
			data:{
	       		"entityClass" : "com.app.miwawa.api.eam.entity.view.ClassesView",
	          "and[0][operator]": "EQ",
	          "and[0][fieldName]": "type",					
	          "and[0][fieldValue]": "早教",
	          "and[1][operator]": "EQ",
	          "and[1][fieldName]": "week",					
	          "and[1]][fieldValue]": week,	
	          "and[2][operator]": "EQ",
	          "and[2][fieldName]": "roomid",					
	          "and[2][fieldValue]": jQuery("#room").val(),
	          "and[3][operator]": "EQ",
	          "and[3][fieldName]": "invalid",					
	          "and[3][fieldValue]": "F"
	  	},
	  	success:function(data){
	  		var list = data.rows;
	  		for(var i=0; i<list.length; i++){
	  			var time = $moment("2016-09-14 "+list[i].time);
		  			if(list[i].id != classes.id && ($moment("2016-09-14 "+jQuery("#lessonTime").val()+":00").add(45,"m").isAfter(time) && time.isAfter($moment("2016-09-14 "+jQuery("#lessonTime").val()+":00").add(-45,"m")) ) ){
		  				classesname = list[i].name;
		  				roomname = list[i].room;
		  				stamp = true;
		  				break;
		  			} 
	  		}		
	  	}
		});
		return stamp;
	}
	
	// 提交行编辑前，设置表单数据
	function setFormData(dest, orig){
		jQuery("#teacherid", orig).val(teacher.teacherid);
		jQuery("#classesid", orig).val(teacher.classesid);
		return true;
	}
	
	// 更新负责老师收费项
	var teacher;
	function handlerUpdate(trigger, index){
		jQuery("[data-toggle='tooltip']","#table-teacher").tooltip("destroy");
		
		var _opts = jQuery(trigger).data();
				teacher = _opts.rowdata;
		
		jQuery("#table-teacher").bootstrapTable("updateRow",{
			index: index,
			row: createEditRow(_opts.rowdata, _opts.tableSource)
		});
		
		function createEditRow(row, target){
			jQuery(target).append("<input type='hidden' name='id' value='"+row.chargeid+"'>");
			
			return {
				id:   		"edit",
	      name: 		row.name,
	      sex: 			row.sex,
	      mobile: 	row.mobile,
	      method: 	createInput('method',	'select', 'ext-text', row.method),
	      amount: 	createInput('amount',	'number', 'ext-text', row.amount),
	      operator: createButton(target)
			};
		}
		
		// 创建输入框
		function createInput(name, type, ext, value){
			switch(type){
				case 'number': 
					return '<input name="'+name+'" id="'+name+'" type="'+type+'" class="form-control '+ext+'" value="'+(value ? value : '10.00')+'">';
				case 'select': 
					return '<select name="'+name+'" id="'+name+'" class="form-control">'
								+	'<option '+(value == '按课时' ? 'selected="selected"' : '')+' value="按课时">按课时</option>'
								+ '<option '+(value == '按人头' ? 'selected="selected"' : '')+' value="按人头">按人头</option>'
								+'</select>';
			}
		}
		
		// 创建按钮
		function createButton(target){
			return ""
						+"<span class='table-editor-tools'>"
						+"	<button type='button' class='btn btn-danger  btn-xs' onclick='handlerCancelRow(\""+target+"\", true);' data-toggle='tooltip' data-placement='top' title='取消'><i class='icon ion-close-circled'></i></button>"
						+"	<button type='button' class='btn btn-success btn-xs' onclick='handlerSubmitRow(\""+target+"\",\"setFormData\");' data-toggle='tooltip' data-placement='top' title='确认'><i class='icon ion-checkmark-circled'></i></button>"
						+"</span>";
		}
		
		jQuery("[data-toggle='tooltip']","#table-teacher").tooltip({html:true, container:"html", trigger:'hover'});
	}
	
	// 删除负责老师
	function handlerDelete(trigger, index){
		var _opts = jQuery(trigger).data(), rowdata = _opts.rowdata;
		jQuery.ajaxsend({
			url:"/miwawa/{dbname}/classes/relation/delete".replace("{dbname}",dbname),
			data:{
				"id":rowdata.id,
				"teacherid":rowdata.teacherid
			},
			success:function(data){
				if(data && data["success"]) {
					jQuery("#table-teacher").bootstrapTable("refresh");
				}
			}
		});
	}
	
	// 切换签到历史的日期
	function handlerSwitch(month){
		var txtdate = month == 0 ? jQuery('[data-now]').text().split(" ")[0] : jQuery('#classes-time').text().replace('年','-').replace('月','-01');
		var nowdate = $moment(txtdate);
		var newdate = nowdate.add(month, 'M');
		createHistory(newdate);
	}
	
	// 查询签到历史数据并创建列表
	function createHistory(nowdate){
		jQuery("#classes-time").text(nowdate.format('YYYY年MM月'));
		var columns = getColumns(nowdate);
		jQuery.ajaxsend({
			url:"/miwawa/{dbname}/classes/check/history".replace("{dbname}",dbname),
			data:{
				"item":"早教",
				"checkDate":nowdate.format('YYYY-MM-DD'),
				"classesId":classes.id
			},
			success:function(data){
				if(data){
					jQuery("#table-history").bootstrapTable("refreshOptions",{ columns:columns, data:data });
				}
			}
		});
	}
	
	// 返回签到历史表头
	function getColumns(nowdate){
		var week = jQuery("#lessonWeek").val();
		var colums = [{checkbox:true},{field: 'student', title: '会员', align: 'center'}];
		
		var from = $moment(nowdate).startOf('month');
		var over = $moment(nowdate).endOf('month');
		
		  
		for(;from <= over;from.add(1, 'd')){
			if(jQuery.utils.week[week] == from.isoWeekday()){
				var title = from.format('YYYY-MM-DD');
				colums.push({
					field: title, 
					title: createTitle(title, week)+createButton(title), 
					align: 'center', 
					formatter: 'renderWeek'
				});
			}
		}
		return colums;
	}
	
//-->
</script>